//
//  XZ_BaseWKWebViewController.m
//  Project_Demo
//
//  Created by caoxiaozhu on 2018/7/12.
//  Copyright © 2018年 caoxiaozhu. All rights reserved.
//

#import "XZ_BaseWKWebViewController.h"

@interface XZ_BaseWKWebViewController ()

@property(nonatomic,strong)UIButton *alertButton;
@property(nonatomic,strong)WKWebViewConfiguration *configuration;
@property(nonatomic,strong)WKUserContentController *userController;
@property(nonatomic,strong)NSURLRequest *request;
@property(nonatomic,strong)NSString *jsName;
@property(nonatomic, strong)UIProgressView * progressView;


@end

@implementation XZ_BaseWKWebViewController

- (WKWebView *)mainWebView{
    
    if (_mainWebView == nil) {
        _configuration = [[WKWebViewConfiguration alloc] init];
         _userController= [[WKUserContentController alloc] init];
        _configuration.userContentController = _userController;
        _mainWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) configuration:_configuration];
        _mainWebView.navigationDelegate = self;
        _mainWebView.UIDelegate = self;
    }
    return _mainWebView;
}

-(void)viewWillAppear:(BOOL)animated{
    
    [self.mainWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
    
    [self.mainWebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
}

//添加KVO监听

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    
    //加载进度值
    
    if ([keyPath isEqualToString:@"estimatedProgress"])
        
    {
        
        if (object == self.mainWebView)
            
        {
            
            [self.progressView setAlpha:1.0f];
            
            [self.progressView setProgress:self.mainWebView.estimatedProgress animated:YES];
            
            if(self.mainWebView.estimatedProgress >= 1.0f)
                
            {
                
                [UIView animateWithDuration:0.5f
                 
                                      delay:0.3f
                 
                                    options:UIViewAnimationOptionCurveEaseOut
                 
                                 animations:^{
                                     
                                     [self.progressView setAlpha:0.0f];
                                     
                                 }
                 
                                 completion:^(BOOL finished) {
                                     
                                     [self.progressView setProgress:0.0f animated:NO];
                                
                                 }];
            }
        }
        else
    
        {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
    
    //网页title
    
    else if ([keyPath isEqualToString:@"title"])
        
    {
        
        if (object == self.mainWebView)
            
        {
            
            self.navigationItem.title = self.mainWebView.title;
            
        }
        
        else
            
        {
            
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
            
        }
        
    }
    
    else
        
    {
        
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        
    }
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation

{
    
    self.progressView.hidden = NO;
    
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    
    [self.view bringSubviewToFront:self.progressView];
    
}

// WKNavigationDelegate 页面加载完成之后调用

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation

{
    //加载完成后隐藏progressView
    
    self.progressView.hidden = YES;

    //修改字体大小 300%
    
    [ webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '100%'" completionHandler:nil];
    
    //修改字体颜色  #9098b8
    
    [webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= '#222222'" completionHandler:nil];
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    
    //加载失败同样需要隐藏progressView
    
    self.progressView.hidden = YES;
    
    [self.mainWebView removeFromSuperview];
    
    //    [self.view addSubview:self.blankPageView];
    
}

-(void)showWebViewWith:(NSString *)url localHtml:(NSString *)fileName jsActionNameArr:(NSArray *)nameArr{
    
    _localHtmlName = fileName;
    _urlStr = url;
    [self setupUrl];
    [self setJSNameArr:nameArr];
    [self.view addSubview:self.mainWebView];
}


-(void)setupUrl{
    
    if (_localHtmlName) {
       NSString * urlName = [[[NSBundle mainBundle] bundlePath]  stringByAppendingPathComponent:_localHtmlName];
        _request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:urlName]];
    }else{
        NSURL *url = [NSURL URLWithString:_urlStr];
        _request = [NSURLRequest requestWithURL:url];
    }
    
    [self.mainWebView loadRequest: _request];
}

-(void)setJSNameArr:(NSArray *)jsNameArr{
    for (int i=0; i<jsNameArr.count; i++) {
        [_userController addScriptMessageHandler:self name:jsNameArr[i]];
    }
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
//    NSLog(@"messagename==>%@",message.name);
    
    self.JSActionBlock(message.name,message.body);
    
//    if ([message.name isEqualToString:@"currentCookies"]) {
////        baseview *baseView = [baseview new];
////        [self.navigationController pushViewController:baseView animated:true];
//        
//        NSString *cookiesStr = message.body;
//        NSLog(@"当前的cookie为： %@", cookiesStr);
//        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"JS调用的OC回调方法" preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction *action = [UIAlertAction actionWithTitle:@"ok" style:UIAlertActionStyleCancel handler:nil];
//        [alert addAction:action];
//        [self presentViewController:alert animated:YES completion:nil];
//    }
}

-(UIProgressView *)progressView

{
    
    if (!_progressView) {
        
        _progressView =[[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 1)];
         
        _progressView.backgroundColor = [UIColor whiteColor];
        
        _progressView.progressTintColor= [UIColor redColor];//设置已过进度部分的颜色
        
        _progressView.trackTintColor= [UIColor lightGrayColor];//设置未过进度部分的颜色
        
        //设置进度条的高度，下面这句代码表示进度条的宽度变为原来的1倍，高度变为原来的1.5倍.
        
        self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
        
        [self.view addSubview:_progressView];
        
    }
    
    return _progressView;
    
}

//移除监听者

- (void)dealloc {
    
    [self.mainWebView removeObserver:self forKeyPath:@"estimatedProgress"];
    
    [self.mainWebView removeObserver:self forKeyPath:@"title"];
    
}

@end
